package com.server.common.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.server.common.VO.Oauth2ToeknVO;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Classname FengRui
 * @Description 微信相关工具包
 * @Date 2022-11-28 12:46
 */
@Component
@RequiredArgsConstructor
public class WxUtils
{
    private final StringRedisTemplate stringRedisTemplate;


    private final static String ACCESS_TOKEN_TWO = "ACCESS_TOKEN_TWO";

//    @Value("${wx.appid}")
    private String appid;
//    @Value("${wx.secret}")
    private String secret;

    public Oauth2ToeknVO refresh_token(String refresh_token){
        HttpRequest get = HttpUtil.createGet("https://api.weixin.qq.com/sns/oauth2/refresh_token");
        Map<String, Object> map = new HashMap<>();
        map.put("appid",appid);
        map.put("grant_type","refresh_token");
        map.put("refresh_token",refresh_token);
        String body = get.form(map).execute().body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        Integer errcode = jsonObject.getInteger("errcode");
        if(errcode != null){
            throw new RuntimeException(jsonObject.getString("errmsg"));
        }
        return JSONObject.parseObject(body,Oauth2ToeknVO.class);
    }

    public Oauth2ToeknVO getAccessToken(String code){
        HttpRequest get = HttpUtil.createGet("https://api.weixin.qq.com/sns/oauth2/access_token");
        Map<String, Object> map = new HashMap<>();
        map.put("appid",appid);
        map.put("CODE",code);
        map.put("secret",secret);
        map.put("grant_type","authorization_code");
        String body = get.form(map).execute().body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        Integer errcode = jsonObject.getInteger("errcode");
        if(errcode != null){
            throw new RuntimeException(jsonObject.getString("errmsg"));
        }
        Oauth2ToeknVO oauth2ToeknVO = JSONObject.parseObject(body, Oauth2ToeknVO.class);
        if(oauth2ToeknVO != null && StringUtils.isNotEmpty(oauth2ToeknVO.getOpenid())){
            oauth2ToeknVO.setExpires_in(System.currentTimeMillis()+(oauth2ToeknVO.getExpires_in()*1000));
            stringRedisTemplate.opsForValue().set(ACCESS_TOKEN_TWO+"_"+oauth2ToeknVO.getOpenid(),JSONObject.toJSONString(oauth2ToeknVO),oauth2ToeknVO.getExpires_in()*10, TimeUnit.SECONDS);
        }
        return JSONObject.parseObject(body,Oauth2ToeknVO.class);
    }

    public Oauth2ToeknVO getAccessToken2(String openId){
        String token = stringRedisTemplate.opsForValue().get(ACCESS_TOKEN_TWO + "_" + openId);
        if (StringUtils.isNotEmpty(token)){
            Oauth2ToeknVO oauth2ToeknVO = JSONObject.parseObject(token, Oauth2ToeknVO.class);
            if (oauth2ToeknVO.getExpires_in()<System.currentTimeMillis()){
                    Oauth2ToeknVO refreshToken = refresh_token(oauth2ToeknVO.getRefresh_token());
                    if(oauth2ToeknVO != null && StringUtils.isNotEmpty(oauth2ToeknVO.getOpenid())){
                        refreshToken.setExpires_in(System.currentTimeMillis()+(oauth2ToeknVO.getExpires_in()*1000));
                        stringRedisTemplate.opsForValue().set(ACCESS_TOKEN_TWO+"_"+oauth2ToeknVO.getOpenid(),JSONObject.toJSONString(oauth2ToeknVO),oauth2ToeknVO.getExpires_in()*10, TimeUnit.SECONDS);
                    }
                    return refreshToken;
            }else{
                return oauth2ToeknVO;
            }
        }
        return null;
    }
}
